/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.ove.openmath.jome.ctrl.amto;

/**
 *
 * @author Mr.Sam
 */
import fr.ove.openmath.jome.ctrl.linear.events.LinearParserEvent;
import fr.ove.openmath.jome.ctrl.amto.Function;

/**
* The abstract math tree object of the partial differentiation.
*
* @author © 2000 DIRAT Laurent
* @version 1.0  23/02/2000
*/
public class PartialDifferentiation extends Function {
    /**
    * The constructor.
    */
    public PartialDifferentiation() {
        super("pdiff");
    }
    
    /**
    * "Flushes" the object as a sequence of events for the building of the model
    */
    public void flush() {
        LinearParserEvent linearParserEvent = new LinearParserEvent(getEventSource());
        // Le format est une liste contenant les indexes des variables de dérivation dans 
        // la liste des variables liées du bind qui suit la liste.
        // Ex, qque chose comme : pdiff([1, 3], lambda([x,y,z], x*y*z)) = diff(x*y*z, x, z)
        
        // The opening
        linearParserEvent.setToken(opening, param);
        fireLinearParserEvent(linearParserEvent);
        
        
        AbstractMathTreeObject list = (AbstractMathTreeObject) getChild(0);
        AbstractMathTreeObject lambda = (AbstractMathTreeObject) getChild(1);
        
        // On envoie l'objet de la lambda expression, i.e. ce qui est dérivé
        int nbChildren = lambda.getNbChildren();
        int count = nbChildren - 1;
        flushChild(lambda.getChild(count), count);
        
        // On envoie maintenant les variables séparées par des séparateurs
        nbChildren = list.getNbChildren();
        AnInteger listElement;
        int listElementValue;
        for (int i = 0; i < nbChildren; i++) {
            listElement = (AnInteger) list.getChild(i);
            
            try {
                listElementValue = Integer.parseInt((String) listElement.param);
                if ((listElementValue > 0) && (listElementValue <= count)) {
                    linearParserEvent.setToken(token, null);
                    fireLinearParserEvent(linearParserEvent);
                    flushChild(lambda.getChild(listElementValue-1), i);
                }
            }
            catch (NumberFormatException nfe) {
                nfe.printStackTrace();
            }
        }
        
        // The closing
        linearParserEvent.setToken(closing, null);
        fireLinearParserEvent(linearParserEvent);
    }
}